/**
 * 权限监控管理器
 * 
 * 实现权限判断的日志记录和监控功能
 * 便于后续权限问题的排查和优化
 * 
 * @author Wu.Liang
 * @date 2025-01-30
 */
import { ref } from 'vue'

// 权限监控日志级别
export enum PermissionLogLevel {
  DEBUG = 'debug',
  INFO = 'info',
  WARN = 'warn',
  ERROR = 'error'
}

// 权限监控日志项
export interface PermissionLogItem {
  id: string
  timestamp: number
  level: PermissionLogLevel
  module: string
  action: string
  userId?: number
  username?: string
  userType?: string
  permission?: string
  result: boolean
  message: string
  details?: any
  duration?: number
}

// 权限监控配置
export interface PermissionMonitorConfig {
  enabled: boolean
  logLevel: PermissionLogLevel
  maxLogItems: number
  enablePerformanceMonitoring: boolean
  enableErrorTracking: boolean
}

// 全局权限监控状态
const permissionLogs = ref<PermissionLogItem[]>([])
const monitorConfig = ref<PermissionMonitorConfig>({
  enabled: true,
  logLevel: PermissionLogLevel.INFO,
  maxLogItems: 1000,
  enablePerformanceMonitoring: true,
  enableErrorTracking: true
})

/**
 * 权限监控管理器
 */
export class PermissionMonitor {
  private static logIdCounter = 0
  
  /**
   * 生成日志ID
   */
  private static generateLogId(): string {
    return `perm_${Date.now()}_${++this.logIdCounter}`
  }
  
  /**
   * 检查是否应该记录日志
   */
  private static shouldLog(level: PermissionLogLevel): boolean {
    if (!monitorConfig.value.enabled) return false
    
    const levelOrder = {
      [PermissionLogLevel.DEBUG]: 0,
      [PermissionLogLevel.INFO]: 1,
      [PermissionLogLevel.WARN]: 2,
      [PermissionLogLevel.ERROR]: 3
    }
    
    return levelOrder[level] >= levelOrder[monitorConfig.value.logLevel]
  }
  
  /**
   * 添加权限日志
   */
  static addLog(
    level: PermissionLogLevel,
    module: string,
    action: string,
    result: boolean,
    message: string,
    details?: any,
    duration?: number
  ): void {
    if (!this.shouldLog(level)) return
    
    const logItem: PermissionLogItem = {
      id: this.generateLogId(),
      timestamp: Date.now(),
      level,
      module,
      action,
      result,
      message,
      details,
      duration
    }
    
    // 添加到日志列表
    permissionLogs.value.push(logItem)
    
    // 限制日志数量
    if (permissionLogs.value.length > monitorConfig.value.maxLogItems) {
      permissionLogs.value = permissionLogs.value.slice(-monitorConfig.value.maxLogItems)
    }
    
    // 控制台输出
    const logMethod = level === PermissionLogLevel.ERROR ? 'error' : 
                     level === PermissionLogLevel.WARN ? 'warn' : 
                     level === PermissionLogLevel.INFO ? 'info' : 'log'
    
    const logPrefix = `[权限监控][${module}][${action}]`
    const logMessage = `${logPrefix} ${message} (结果: ${result})`
    
    if (duration !== undefined) {
      console[logMethod](`${logMessage} (耗时: ${duration}ms)`, details || '')
    } else {
      console[logMethod](logMessage, details || '')
    }
  }
  
  /**
   * 记录权限检查
   */
  static logPermissionCheck(
    module: string,
    action: string,
    permission: string,
    result: boolean,
    userId?: number,
    username?: string,
    userType?: string,
    duration?: number
  ): void {
    const level = result ? PermissionLogLevel.INFO : PermissionLogLevel.WARN
    const message = `权限检查: ${permission}`
    
    this.addLog(level, module, action, result, message, {
      permission,
      userId,
      username,
      userType
    }, duration)
  }
  
  /**
   * 记录权限错误
   */
  static logPermissionError(
    module: string,
    action: string,
    error: Error | string,
    details?: any
  ): void {
    const message = error instanceof Error ? error.message : error
    this.addLog(PermissionLogLevel.ERROR, module, action, false, message, details)
  }
  
  /**
   * 记录权限性能
   */
  static logPermissionPerformance(
    module: string,
    action: string,
    duration: number,
    details?: any
  ): void {
    if (!monitorConfig.value.enablePerformanceMonitoring) return
    
    const level = duration > 1000 ? PermissionLogLevel.WARN : PermissionLogLevel.DEBUG
    const message = `权限检查性能: ${duration}ms`
    
    this.addLog(level, module, action, true, message, details, duration)
  }
  
  /**
   * 获取权限日志
   */
  static getLogs(
    level?: PermissionLogLevel,
    module?: string,
    limit?: number
  ): PermissionLogItem[] {
    let logs = permissionLogs.value
    
    if (level) {
      logs = logs.filter(log => log.level === level)
    }
    
    if (module) {
      logs = logs.filter(log => log.module === module)
    }
    
    if (limit) {
      logs = logs.slice(-limit)
    }
    
    return logs
  }
  
  /**
   * 清除权限日志
   */
  static clearLogs(): void {
    permissionLogs.value = []
    console.log('[权限监控] 日志已清除')
  }
  
  /**
   * 获取权限统计信息
   */
  static getStatistics(): {
    totalLogs: number
    successCount: number
    failureCount: number
    errorCount: number
    averageDuration: number
    moduleStats: Record<string, { count: number; success: number; failure: number }>
  } {
    const logs = permissionLogs.value
    const totalLogs = logs.length
    const successCount = logs.filter(log => log.result).length
    const failureCount = logs.filter(log => !log.result && log.level !== PermissionLogLevel.ERROR).length
    const errorCount = logs.filter(log => log.level === PermissionLogLevel.ERROR).length
    
    const durations = logs.filter(log => log.duration !== undefined).map(log => log.duration!)
    const averageDuration = durations.length > 0 ? durations.reduce((a, b) => a + b, 0) / durations.length : 0
    
    const moduleStats: Record<string, { count: number; success: number; failure: number }> = {}
    logs.forEach(log => {
      if (!moduleStats[log.module]) {
        moduleStats[log.module] = { count: 0, success: 0, failure: 0 }
      }
      moduleStats[log.module].count++
      if (log.result) {
        moduleStats[log.module].success++
      } else {
        moduleStats[log.module].failure++
      }
    })
    
    return {
      totalLogs,
      successCount,
      failureCount,
      errorCount,
      averageDuration,
      moduleStats
    }
  }
  
  /**
   * 更新监控配置
   */
  static updateConfig(config: Partial<PermissionMonitorConfig>): void {
    monitorConfig.value = { ...monitorConfig.value, ...config }
    console.log('[权限监控] 配置已更新:', monitorConfig.value)
  }
  
  /**
   * 导出权限日志
   */
  static exportLogs(): string {
    return JSON.stringify({
      config: monitorConfig.value,
      statistics: this.getStatistics(),
      logs: permissionLogs.value
    }, null, 2)
  }
}

// 导出监控状态
export const usePermissionMonitor = () => {
  return {
    logs: permissionLogs,
    config: monitorConfig,
    addLog: PermissionMonitor.addLog.bind(PermissionMonitor),
    logPermissionCheck: PermissionMonitor.logPermissionCheck.bind(PermissionMonitor),
    logPermissionError: PermissionMonitor.logPermissionError.bind(PermissionMonitor),
    logPermissionPerformance: PermissionMonitor.logPermissionPerformance.bind(PermissionMonitor),
    getLogs: PermissionMonitor.getLogs.bind(PermissionMonitor),
    clearLogs: PermissionMonitor.clearLogs.bind(PermissionMonitor),
    getStatistics: PermissionMonitor.getStatistics.bind(PermissionMonitor),
    updateConfig: PermissionMonitor.updateConfig.bind(PermissionMonitor),
    exportLogs: PermissionMonitor.exportLogs.bind(PermissionMonitor)
  }
} 